﻿using UnityEngine;
using System;
using LitJson;
using System.Collections;
using System.Collections.Generic;

public class YoutubeSearch : MonoBehaviour {

    private const string URL_YOUTUBE_SEARCH = "http://codingthebits.wc.lt/musicadagalera/youtube.php";
    private const int MAX_RESULTS = 10;

    private string text = "";

    public List<YoutubeVideoData> videoData = new List<YoutubeVideoData>();

	void Start () {
	
	}
	
    void OnGUI() {
        text = GUILayout.TextField(text);

        if (GUILayout.Button("Procurar")) {
            search(text);
        }
    }


    public void search(string keyword) {
        StartCoroutine(searchOnYoutube(keyword));
    }

    IEnumerator searchOnYoutube(string keyword) {

        WWWForm form = new WWWForm();
        form.AddField("q", keyword);
        form.AddField("maxResults", MAX_RESULTS);

        WWW www = new WWW(URL_YOUTUBE_SEARCH,form);

        yield return www;

        if (www.error != null) {
            Debug.LogError(www.error);
        } else {
            Debug.Log(www.text);
            readJson(www.text);
        }
    }

    public void readJson(string json) {
        JsonData data = JsonMapper.ToObject(json);

        for (int i = 0; i < data.Count; i++) {
            YoutubeVideoData youtubeData = new YoutubeVideoData();
            youtubeData.videoID = data[i]["id"]["videoId"].ToString();
            youtubeData.title = data[i]["snippet"]["title"].ToString();
            youtubeData.description = data[i]["snippet"]["description"].ToString();
            string url = data[i]["snippet"]["thumbnails"]["default"]["url"].ToString();
            StartCoroutine(getImageFromURL(url, youtubeData, whenImageLoad));
            videoData.Add(youtubeData);
        }
    }

    public void whenImageLoad(Texture2D pic, YoutubeVideoData data) {
        data.pic = pic;
    }

    public IEnumerator getImageFromURL(string url, YoutubeVideoData data, Action<Texture2D, YoutubeVideoData> callback) {

        WWW www = new WWW(url);

        yield return www;

        if (www.error == null) {
            if (www.texture != null) {
                callback(www.texture, data);
            } else {
                Debug.LogError("Não foi possivel achar uma imagem");
            }
        } else {
            Debug.LogError(www.error);
        }
    }

}
